package com.dq.service.record.impl;

import com.dq.controller.in.query.ServiceQuery;
import com.dq.domain.service.ServiceProjectRecordCentre;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.record.ServiceProjectRecordCentreService;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @Author luchangtong
 * @Date 2019/11/25 17:04
 */
@Service
public class ServiceProjectRecordCentreServiceImpl implements ServiceProjectRecordCentreService {

    @PersistenceContext
    private EntityManager entityManager;
    @Override
    public List<ServiceProjectRecordCentre> findByUser(ServiceQuery serviceQuery, SysUser user) {
        StringBuilder hql = new StringBuilder("select u from ServiceProjectRecordCentre u where u.deleted=false");
        Query query = createWhereHql(serviceQuery,user,hql);
        query.setFirstResult((serviceQuery.getPage()-1)*serviceQuery.getSize());
        query.setMaxResults(serviceQuery.getSize());
        List<ServiceProjectRecordCentre> serviceProjectRecordCentres = query.getResultList();
        return serviceProjectRecordCentres;
    }

    @Override
    public Long countByWhere(ServiceQuery serviceQuery, SysUser user) {
        StringBuilder hql = new StringBuilder("select count(u) from ServiceProjectRecordCentre u where u.deleted=false");
        Query query = createWhereHql(serviceQuery,user,hql);
        return new Long((long) query.getResultList().get(0));
    }

    public Query createWhereHql(ServiceQuery serviceQuery, SysUser user,StringBuilder hql){
        hql.append(" and u.serviceRecord.wxUser =:wxUser");
        hql.append(" ORDER BY u.createTime desc");
        Query query  = entityManager.createQuery(hql.toString());
        query.setParameter("wxUser",user);
        return query;
    }
}
